package com.imooc.utils;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileUtils {

    public static String saveFile(MultipartFile[] files, String fileSpace, String uploadPathDB) {
        String fileName = files[0].getOriginalFilename();
        return saveFile(files, fileSpace, uploadPathDB, fileName);

    }

    public static String saveFile(MultipartFile[] files, String fileSpace, String uploadPathDB, String fileName) {

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        //获取文件的名称
    /*    String fileName = files[0].getOriginalFilename();
        //todo 判断文件名是不是空的*/
        //获取保存的绝对路径
        String path = fileSpace + uploadPathDB + "/" + fileName;
        uploadPathDB += ("/" + fileName);
        File outFile = new File(path);


        //判断文件路径是否存在
        if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
            outFile.getParentFile().mkdirs(); //创建文件夹
        }
        try {
            fileOutputStream = new FileOutputStream(outFile);
            inputStream = files[0].getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return uploadPathDB;
    }

    public static String saveFileOne(MultipartFile files, String fileSpace, String uploadPathDB ) {
        String fileName = files .getOriginalFilename();
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        //获取文件的名称
    /*    String fileName = files[0].getOriginalFilename();
        //todo 判断文件名是不是空的*/
        //获取保存的绝对路径
        String path = fileSpace + uploadPathDB + "/" + fileName;
        uploadPathDB += ("/" + fileName);
        File outFile = new File(path);


        //判断文件路径是否存在
        if (outFile.getParentFile() != null || !outFile.getParentFile().isDirectory()) {
            outFile.getParentFile().mkdirs(); //创建文件夹
        }
        try {
            fileOutputStream = new FileOutputStream(outFile);
            inputStream = files.getInputStream();
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return uploadPathDB;
    }

}
